<template>
  <el-dialog
    append-to-body
    :title="title"
    :visible.sync="dialogVisible"
    width="500px"
  >
    <el-form ref="formRef" style="margin-right: 10px" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="ruleForm.userName" clearable />
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input v-model="ruleForm.phonenumber" clearable />
      </el-form-item>
      <el-form-item v-if="!ruleForm.userId" label="密码" prop="password">
        <el-input v-model="ruleForm.password" clearable />
      </el-form-item>
      <el-form-item label="营业执照号" prop="licenseNum">
        <el-input v-model="ruleForm.licenseNum" clearable />
      </el-form-item>
      <el-form-item label="种植面积" prop="plantArea">
        <el-input v-model="ruleForm.plantArea" clearable type="number" />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptIds">
        <ElSelectTree
          v-model="ruleForm.deptIds"
          :data="deptList"
          node-key="deptId"
          multiple
          :props="{
            label: 'deptName',
            children: 'children'
          }"
          check-strictly
        />
      </el-form-item>
      <el-form-item label="所属角色" prop="roleIds">
        <ElSelectTree
          v-model="ruleForm.roleIds"
          :data="roleList"
          node-key="roleId"
          multiple
          :props="{
            label: 'roleName',
            children: 'children'
          }"
          check-strictly
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>

</template>

<script>
import { validPhone } from '@/utils/validate';
import { http_dept, http_user, http_role } from '@/api';
import { listToTree } from '@/utils';
import { encrypt } from '@/utils/JSEncrypt';

const checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('不能为空'));
  }
  if (!validPhone(value)) {
    return callback(new Error('手机号不合法'));
  }
  callback();
};

const checkArr = (rule, value, callback) => {
  if (!value || !value.length) {
    return callback(new Error('不能为空'));
  }
  callback();
};
export default {
  name: 'User',
  data() {
    return {
      deleteKey: 'userId',
      ruleForm: {
        userId: undefined,
        userName: '',
        phonenumber: '',
        password: '',
        licenseNum: '',
        plantArea: '',
        avatar: '',
        deptIds: [],
        roleIds: []
      },
      resetForm: {
        userId: undefined,
        userName: '',
        phonenumber: '',
        password: '',
        licenseNum: '',
        plantArea: '',
        avatar: '',
        deptIds: [],
        roleIds: []
      },
      rules: {
        userName: [
          { required: true, message: '不能为空' }
        ],
        phonenumber: [{ required: true, validator: checkPhone }],
        password: [
          { required: true, message: '不能为空' }
        ],
        licenseNum: [
          { required: true, message: '不能为空' }
        ],
        plantArea: [
          { required: true, message: '不能为空' }
        ],
        deptIds: [
          { required: true, validator: checkArr }
        ]
      },
      deptList: [],
      roleList: [],
      dialogVisible: false
    }
  },
  computed: {
    title() {
      return this.ruleForm[this.deleteKey] ? '编辑' : '添加'
    }
  },
  methods: {
    getDeptList() {
      http_dept.list().then(res => {
        this.deptList = listToTree(res.data || [], 'deptId')
      })
      http_role.list().then(res => {
        this.roleList = res.rows
      })
    },
    getRoleList() {},
    onAdd() {
      this.getDeptList()
      this.ruleForm = {
        ...this.resetForm
      }
      this.dialogVisible = true
    },
    onEdit(row) {
      this.getDeptList()
      for (const ruleFormKey in this.ruleForm) {
        this.ruleForm[ruleFormKey] = row[ruleFormKey]
      }
      this.ruleForm.deptIds = row.depts.map(el => el.deptId)
      this.ruleForm.roleIds = row.roles.map(el => el.roleId)
      this.dialogVisible = true
    },
    onSave() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          http_user[this.ruleForm[this.deleteKey] ? 'update' : 'create']({
            ...this.ruleForm,
            plantArea: Number(this.ruleForm.plantArea),
            password: encrypt(this.ruleForm.password)
          }).then((res) => {
            this.$message.success(res.msg)
            this.$emit('get-page')
            this.onClose()
          })
        }
      })
    },
    onClose() {
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped lang="scss">
</style>
